package com.huizhonglm.diap.ui.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.API;
import com.huizhonglm.diap.api.CommonResponse;
import com.huizhonglm.diap.api.HttpCallback;
import com.huizhonglm.diap.api.Status;
import com.huizhonglm.diap.api.model.user.ChecksumResponse;
import com.huizhonglm.diap.api.model.wallet.BankCardAddParams;
import com.huizhonglm.diap.api.model.wallet.BankCardCheckParams;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.presenters.user.ChecksumPresenter;
import com.huizhonglm.diap.presenters.wallet.BankCardAddPresenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.iView.ChecksumIView;
import com.huizhonglm.diap.ui.views.BankPickerView;
import com.huizhonglm.diap.ui.wallet.iView.BankCardAddIView;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 绑定银行卡
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-22 14:00
 */
public class BankCardAddActivity extends BaseActivity implements ChecksumIView, BankCardAddIView ,View.OnClickListener,
        BankPickerView.OnBankSelectedListener {

    private BankPickerView bankPicker;
    private EditText cardHolderEdt;
    private TextView bankNameTxt;
    private EditText cardNoEdt;
    private EditText phoneNumEdt;
    private CheckBox userRuleCbx;
    private TextView userRultTxt;

    private String bankName;

    private BankCardAddPresenter mPresenter;

    private ChecksumPresenter checksumPresenter;

    /**
     * 是否开始计时
     */
    private boolean isStarted = false;
    /**
     * 最大时间(60秒)
     */
    private int time = 60;
    /**
     * 计时器
     */
    private Timer timer;
    /**
     * 计时器线程
     */
    private TimerTask task;
    /**
     * 消息处理器
     */
    private TimerHandler timerHandler;
    private EditText checkSumEdt;
    private TextView getChecksumTxt;

    private String checksum;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bank_card_add);
        setBackEvent(this, null);
        mPresenter = new BankCardAddPresenter(this);
        checksumPresenter = new ChecksumPresenter(this);
        timerHandler = new TimerHandler(this);
        assignViews();
    }

    @Override
    protected void assignViews() {
        View complateTxt = findViewById(R.id.title_cmpl_txt);
        bankPicker = new BankPickerView(this, findViewById(R.id.binding_card_page), this);
        View bankName = findViewById(R.id.bank_name_layout);
        cardHolderEdt = (EditText) findViewById(R.id.card_holder_edt);
        bankNameTxt = (TextView) findViewById(R.id.bank_name_txt);
        cardNoEdt = (EditText) findViewById(R.id.card_no_edt);
        phoneNumEdt = (EditText) findViewById(R.id.phone_number_edt);
        checkSumEdt = (EditText) findViewById(R.id.check_sum_edt);
        getChecksumTxt = (TextView) findViewById(R.id.get_checksum_txt);
        userRuleCbx = (CheckBox) findViewById(R.id.user_rule_cbx);
        userRultTxt = (TextView) findViewById(R.id.user_rule_txt);

        complateTxt.setOnClickListener(this);
        bankName.setOnClickListener(this);
        getChecksumTxt.setOnClickListener(this);
        userRultTxt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bank_name_layout:
                closeKeyboard(BankCardAddActivity.this);
                bankPicker.show(bankName);
                break;
            case R.id.title_cmpl_txt:
                if (checkInput()) {
                    checkBankInfo();
                }
                break;
            case R.id.user_rule_txt:
                startActivity(new Intent(BankCardAddActivity.this, UserRuleActivity.class));
                break;
            case R.id.get_checksum_txt:
                String phone = phoneNumEdt.getText().toString();
                if (EmptyUtil.isEmpty(phone)){
                    ToastUtil.makeTextShort("请输入手机号码");
                    return;
                } else {
                    if (phone.length() < 11) {
                        ToastUtil.makeTextShort("输入的手机号码无效");
                    }
                }
                phoneNumEdt.setEnabled(false);
                getChecksum(phone);
                break;
        }
    }

    @Override
    public void onBankSelected(String name) {
        this.bankName = name;
        bankNameTxt.setText(name);
    }

    @Override
    public void addBankCardSuccess() {
        hideProgressBar();
        ToastUtil.makeTextShort("添加成功");
        finish();
    }

    @Override
    public void addBankCardFailure() {
        hideProgressBar();
        ToastUtil.makeTextShort("添加失败，请稍后重试");
    }

    @Override
    public void onChecksumSuccess(ChecksumResponse resp) {
        hideProgressBar();
        if (resp != null) {
            switch (resp.getStatus()){
                case Status.SUCCESS:
                    checksum = resp.getChekCode();
                    break;
                case Status.HAS_REG:
                    stopTimer();
                    ToastUtil.makeTextShort("该账号已被注册，请直接登录");
                    break;
                case Status.FAILURE:
                    stopTimer();
                    ToastUtil.makeTextShort("验证码获取失败，请稍后重试");
                    break;
            }
        }
    }

    @Override
    public void onChecksumFailure() {
        phoneNumEdt.setEnabled(true);
        hideProgressBar();
        stopTimer();
        ToastUtil.makeTextShort("验证码获取失败");
    }

    private boolean checkInput(){
        String cardHolder = cardHolderEdt.getText().toString().trim();

        if (EmptyUtil.isEmpty(cardHolder)) {
            ToastUtil.makeTextShort("请填写持卡人");
            return false;
        }
        if (EmptyUtil.isEmpty(bankName)) {
            ToastUtil.makeTextShort("请选择开户行");
            return false;
        }
        if (EmptyUtil.isEmpty(bankName)) {
            ToastUtil.makeTextShort("请填写银行卡号");
            return false;
        }
        if (!userRuleCbx.isChecked()) {
            ToastUtil.makeTextShort("请阅读并同意用户协议");
            return false;
        }

        if (EmptyUtil.isEmpty(checkSumEdt.getText())){
            ToastUtil.makeTextShort("请输入手机验证码");
            return false;
        }

        if (!checkSumEdt.getText().toString().equals(checksum)) {
            ToastUtil.makeTextShort("验证码错误");
            return false;
        }

        return true;
    }

    public void checkBankInfo() {
        showProgressBar();
        final String cardHolder = cardHolderEdt.getText().toString().trim();
        final String cardNo = cardNoEdt.getText().toString().trim();
        final String phoneNum = phoneNumEdt.getText().toString().trim();

        BankCardCheckParams params = new BankCardCheckParams();
        params.userId = UserUtil.getUserId();
        params.userBankNumber = cardNo;
        params.userBankPhone = phoneNum;
        params.userVerificationCode = checksum;
        API.http().post("checkBankInfo", params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                if (!EmptyUtil.isEmpty(result)) {
                    CommonResponse resp = JSON.parseObject(result, CommonResponse.class);
                    if (resp != null && Status.SUCCESS.equals(resp.getStatus())){
                        BankCardAddParams params = new BankCardAddParams();
                        params.userId = UserUtil.getUserId();
                        params.cardHolder = cardHolder;
                        params.cardNo = cardNo;
                        params.bankName = bankName;
                        if (!EmptyUtil.isEmpty(phoneNum)) {
                            params.phoneNum = phoneNum;
                        }
                        mPresenter.addBankCard(params);
                    } else {
                        hideProgressBar();
                        ToastUtil.makeTextShort("实名认证信息和银行卡信息不一致");
                    }
                } else {
                    hideProgressBar();
                    ToastUtil.makeTextShort("实名认证信息和银行卡信息不一致");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                hideProgressBar();
                ToastUtil.makeTextShort("网络异常，请稍后重试");
            }
        });
    }

    private void getChecksum(String phoneNumber){
        showProgressBar();
        startTimer();
        checksumPresenter.getChecksum(phoneNumber, "N");
    }

    private void startTimer() {
        if (!isStarted) {
            isStarted = true;
            getChecksumTxt.setEnabled(false);
            getChecksumTxt.setTextColor(ContextCompat.getColor(this, R.color.darkGray));
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    timerHandler.sendEmptyMessage(0);
                }
            };
            timer.schedule(task, 0, 1000);
        }
    }

    private void stopTimer() {
        if (isStarted) {
            isStarted = false;
            getChecksumTxt.setEnabled(true);
            getChecksumTxt.setText("重新获取");
            getChecksumTxt.setTextColor(ContextCompat.getColor(this, R.color.mainRed));
            if (timer != null && task != null) {
                timer.cancel();
                timer.purge();
                task.cancel();
                task = null;
                timer = null;
            }
        }
    }

    /**
     * 处理消息
     *
     * @param msg 消息
     */
    private void updateTimer(Message msg) {
        switch (msg.what) {
            case 0:
                String text = "*秒后可重新获取";
                if (time > 1) {
                    time--;
                    text = text.replace("*", time + "");
                } else {
                    stopTimer();
                    text = "重新获取";
                    time = 60;
                }
                getChecksumTxt.setText(text);
                break;
        }
    }

    /**
     * 消息处理器
     *
     * @author uthor LiXiaoLong
     * @since 2013-6-18 下午3:56:24
     */
    private static class TimerHandler extends Handler {
        WeakReference<BankCardAddActivity> activity;

        public TimerHandler(BankCardAddActivity acti) {
            activity = new WeakReference<>(acti);
        }

        @Override
        public void handleMessage(Message msg) {
            BankCardAddActivity theActivity = activity.get();
            theActivity.updateTimer(msg);
        }
    }
}
